#include "resource_material.h"
#include "messiah/resource/repo/repo_item.h"
#include "messiah/resource/repo/repository.h"
#include "fileio/fileio.h"

namespace renderit
{
	namespace messiah
	{
		static std::string empty_string;

		bool resource_material_layer::deserialize(tinyxml2::XMLElement* elem)
		{
			layer_name_ = elem->GetChildText("LayerName", "");
			shader_name_ = elem->GetChildText("ShaderName", "");
			tinyxml2::XMLElement* param_elems = elem->FirstChildElement("Parameters");
			std::vector<tinyxml2::XMLElement*> params = param_elems->ChildrenElements("Element");
			parameters_.resize(params.size());
			for (int i = 0; i < params.size(); ++i)
			{
				parameters_[i].key = params[i]->GetChildText("Name", "");
				parameters_[i].val = params[i]->GetChildText("Value", "");
			}
			return true;
		}

		const std::string& resource_material_layer::get_param(const char * key) const
		{
			for (auto& p : parameters_)
			{
				if (p.key == key)
				{
					return p.val;
				}
			}
			return empty_string;
		}

		resource_material::resource_material(repo_item * item)
			: iresource(item)
		{

		}

		bool resource_material::load_resource()
		{
			std::string fullname = "";
			fullname = fullname + "resource.xml";

			tinyxml2::XMLDocument doc;
			tinyxml2::XMLError err = doc.LoadFile(fullname.c_str());
			if (err)
			{
				return false;
			}

			tinyxml2::XMLElement * root_elem = doc.RootElement();
			tinyxml2::XMLElement * entity_elem = root_elem->FirstChildElementMultiLevel("SMaterialData/Root/Entity");
			if (!entity_elem)
			{
				return false;
			}
			tinyxml2::XMLElement * name_elem = entity_elem->FirstChildElement("name");
			if (name_elem)
			{
				name_ = name_elem->GetText();
			}
			tinyxml2::XMLElement * layers_elem = entity_elem->FirstChildElementMultiLevel("info/Layers");
			if (layers_elem)
			{
				std::vector<tinyxml2::XMLElement*> elems = layers_elem->ChildrenElements("Element");
				this->layers_.resize(elems.size());
				for (int i = 0; i < elems.size(); ++i)
				{
					this->layers_[i].deserialize(elems[i]);
				}
			}
			tinyxml2::XMLElement * flag_elem = entity_elem->FirstChildElementMultiLevel("flags/Element");
			if (flag_elem)
			{
				tinyxml2::XMLUtil::ToInt(flag_elem->GetText(), &flag_);
			}
			return true;
		}
	}
}